<template>
  <div class="manager">
    <div class="left" :style="{ width: menuWidth }">
      <!-- <div class="left-tilte">
      </div> -->
      <div class="left-menu">
        <el-menu @select="selectMenu" :collapse="isCollapse">
          <el-sub-menu v-for="(x, y) in menus" :index="x.name">
            <template #title>
              <el-icon>
                <component :is="elicons[x.elicon]" />
              </el-icon>
              <!-- <span :class="'iconfont icon-' + x.icon" style="margin-right: 10px;"></span> -->
              <span> {{ x.title }} </span>
            </template>
            <el-menu-item v-for="a in x.children" :index="a.name">
              <template #title>
                <el-icon>
                  <component :is="elicons[a.elicon]" />
                </el-icon>
                <!-- <span :class="'iconfont icon-' + a.icon" style="margin-right: 10px;"></span> -->
                <span> {{ a.title }} </span>
              </template>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>
    </div>
    <div class="right" :style="{ width: contentWidth }">
      <div class="content">
        <div class="search">
          <el-form ref="searchRef" :model="searchParams" label-width="80px" :inline="true" v-show="showSearch">
            <template v-for="(x, y) in state.searchColumns" :key="y">
              <template v-if="x.name != 'sort' && x.search == 1">
                <el-form-item label="表名" prop="tname" v-if="x.name == 'tname'">
                  <el-select v-model="searchParams.tname" :placeholder="'请选择' + x.title" style="width: 150px;">
                    <el-option v-for="(x, y) in state.tables" :value="x.name" :label="x.name"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="输入方式" prop="input" v-else-if="x.name == 'input'">
                  <el-select v-model="searchParams.input" placeholder="请选择类型" style="width: 150px;">
                    <el-option :value="1" label="文本">文本</el-option>
                    <el-option :value="2" label="选择">选择</el-option>
                    <el-option :value="3" label="时间">时间</el-option>
                    <el-option :value="4" label="链接">链接</el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="父级" prop="pid" v-else-if="x.name == 'pid'">
                  <el-select v-model="searchParams.pid" :placeholder="'请选择' + x.title" style="width: 150px;" clearable>
                    <el-option v-for="x in pidOptions" :value="x.value" :label="x.label"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="类型" prop="type" v-else-if="x.name == 'type'">
                  <el-select v-model="searchParams.type" :placeholder="'请选择' + x.title" style="width: 150px;" clearable>
                    <el-option v-for="x in typeOptions" :value="x.value" :label="x.label"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="可视化" prop="visible" v-else-if="x.name == 'visible'">
                  <el-select v-model="searchParams.visible" :placeholder="'请选择' + x.title" style="width: 150px;">
                    <el-option :value="1" label="是"></el-option>
                    <el-option :value="2" label="否"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="可搜索" prop="search" v-else-if="x.name == 'search'">
                  <el-select v-model="searchParams.search" :placeholder="'请选择' + x.title" style="width: 150px;">
                    <el-option :value="1" label="是"></el-option>
                    <el-option :value="2" label="否"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="x.title" :prop="x.name" v-else>
                  <el-input v-model="searchParams[x.name]" :placeholder="'请输入' + x.title" style="width: 150px;" />
                </el-form-item>
              </template>
            </template>
            <el-form-item label="">
              <el-button @click="getList" type="primary">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="btns">
          <el-button @click="handleCollapse" type="primary" v-if="isCollapse" :icon="elicons.Expand">展开表格</el-button>
          <el-button @click="handleCollapse" v-else :icon="elicons.Fold">收缩表格</el-button>
          <el-button @click="handleAdd" type="primary" :icon="elicons.Plus">新增数据</el-button>
          <el-button @click="batchExcel" type="info" :icon="elicons.FolderAdd">导入数据</el-button>
          <el-dropdown placement="top-start" v-if="isBatch" style="margin: 0 10px;">
            <el-button @click="handleBatch" :icon="elicons.Close">取消操作 </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="exportToExcel">导出Excel</el-dropdown-item>
                <el-dropdown-item @click="exportToJSON">导出JSON</el-dropdown-item>
                <el-dropdown-item>批量删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button @click="handleBatch" type="warning" :icon="elicons.More" v-else>批量操作</el-button>
          <el-button @click="handleSearch" type="danger" :icon="elicons.Search" v-if="showSearch">隐藏搜素</el-button>
          <el-button @click="handleSearch" type="success" :icon="elicons.Search" v-else>显示搜素</el-button>
          <el-button @click="() => { isStructure = true }" type="primary" :icon="elicons.Star">数据结构</el-button>
          <el-button @click="sortData" type="success" :icon="elicons.Filter">整体排序</el-button>
          <el-button @click="allExport" :icon="elicons.Download">全部导出</el-button>
        </div>
        <div class="table">
          <el-table :data="state.lists" style="width: 100%" v-if="state.searchColumns.length > 0" border
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" v-if="isBatch" />
            <el-table-column type="index" width="60" label="顺序" align="center" />
            <template v-for="(x, y) in state.searchColumns" :key="y">
              <template v-if="x.visible == 1">
                <el-table-column v-if="x.name == 'icon'" prop="icon" label="图标" width="60" align="center">
                  <template #default="scope">
                    <span :class="'iconfont icon-' + scope.row.icon"></span>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'elicon'" prop="elicon" label="图标" width="60" align="center">
                  <template #default="scope">
                    <el-icon>
                      <component :is="elicons[scope.row.elicon]" />
                    </el-icon>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'pid'" prop="pid" label="父级" :width="x.width" align="center">
                  <template #default="scope">
                    {{ setPidLabel(scope.row.pid) }}
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'type'" prop="type" label="类型" :width="x.width" align="center">
                  <template #default="scope">
                    {{ setTypeLabel(scope.row.type) }}
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'color'" prop="color" label="颜色" :width="x.width" align="center">
                  <template #default="scope">
                    <div :style="{ width: '20px', height: '20px', background: scope.row.color, margin: '0 auto' }">
                    </div>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'progress'" prop="color" label="进度" :width="x.width"
                  align="center">
                  <template #default="scope">
                    {{ scope.row.progress }}
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'input'" prop="input" label="输入类型" :width="x.width"
                  align="center">
                  <template #default="scope">
                    {{ getInputLabel(scope.row.input) }}
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'visible'" prop="visible" label="可视" :width="x.width"
                  align="center">
                  <template #default="scope">
                    <el-switch v-model="scope.row.visible" :active-value="1" :inactive-value="2" disabled />
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'search'" prop="search" label="搜索" :width="x.width"
                  align="center">
                  <template #default="scope">
                    <el-switch v-model="scope.row.search" :active-value="1" :inactive-value="2" disabled />
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'href'" prop="href" label="链接" :width="x.width" align="center">
                  <template #default="scope">
                    <div style="cursor: pointer;" @click="goToLink(scope.row.href)">{{ scope.row.href }}</div>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'path'" prop="path" label="仓库" :width="x.width" align="center">
                  <template #default="scope">
                    <el-button @click="goToLink(scope.row.path)">{{ scope.row.path }}</el-button>
                  </template>
                </el-table-column>
                <el-table-column v-else-if="x.name == 'start'" prop="start" label="启动" :width="x.width" align="center">
                  <template #default="scope">
                    <el-button @click="goStart(scope.row.start)">启动</el-button>
                  </template>
                </el-table-column>
                <el-table-column v-else :prop="x.name" :label="x.title" :width="x.width" align="center" />
              </template>
            </template>
            <el-table-column label="创建时间" prop="create_time" align="center" width="180px"></el-table-column>
            <el-table-column label="操作" align="center" width="150px" fixed="right">
              <template #default="scope">
                <el-button type="info" :icon="elicons.Message" circle @click="handleDetail(scope.row)" />
                <el-button type="primary" :icon="elicons.Edit" circle @click="handleUpdate(scope.row)" />
                <el-button type="danger" :icon="elicons.Delete" circle @click="handleDelete(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div style="color: black;" v-else>参数为空</div>
        </div>
        <div class="page">
          <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.show"
            :page-sizes="sizes" layout="total, sizes, prev, pager, next" :total="total" background
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
    <div class="hidden">
      <el-dialog :title="state.title" v-model="state.open" width="80%">
        <el-form ref="formRef" :model="form" size="default" label-width="150px">
          <el-row :gutter="20">
            <el-col :span="10" v-for="(x, y) in state.searchColumns">
              <el-form-item :key="y" :label="x.title" :prop="x.name">
                <template v-if="x.name == 'id'">
                  <el-input v-model="form.id" style="width: 150px;margin-right: 10px;" disabled />
                </template>
                <template v-else-if="x.name == 'color'">
                  <!-- <el-color-picker v-model="form.color" show-alpha /> -->
                  <el-input v-model="form.color" :placeholder="'请输入' + x.title"
                    style="width: 150px;margin-right: 10px;" />
                  <input type="color" v-model="form.color" />
                </template>
                <template v-else-if="x.name == 'tname'">
                  <el-select v-model="form.tname" placeholder="请选择" style="width: 200px;">
                    <el-option v-for="x in state.tables" :value="x.name" :label="x.name" :key="y"></el-option>
                  </el-select>
                </template>
                <template v-else-if="x.name == 'type'">
                  <el-select v-model="form.type" placeholder="请选择" style="width: 200px;">
                    <el-option v-for="x in typeOptions" :value="x.value" :label="x.label" :key="y"></el-option>
                  </el-select>
                </template>
                <!-- <template v-else-if="x.name == 'begin'">
              <el-date-picker v-model="form.begin" type="date" placeholder="选择开始日期" />
            </template>
            <template v-else-if="x.name == 'end'">
              <el-date-picker v-model="form.end" type="date" placeholder="选择结束日期" />
            </template> -->
                <template v-else-if="x.name == 'progress'">
                  <el-slider style="width: 300px;margin-left: 10px;" v-model="form.progress" :step="10" show-stops />
                </template>
                <template v-else-if="x.name == 'visible'">
                  <!-- <el-select v-model="form.visible" placeholder="请选择" style="width: 200px;">
                <el-option :value="1" label="是">是</el-option>
                <el-option :value="2" label="否">否</el-option>
              </el-select> -->
                  <el-switch v-model="form.visible" :active-value="1" :inactive-value="2" />
                </template>
                <template v-else-if="x.name == 'search'">
                  <!-- <el-select v-model="form.search" placeholder="请选择" style="width: 200px;">
                <el-option :value="1" label="是">是</el-option>
                <el-option :value="2" label="否">否</el-option>
              </el-select> -->
                  <el-switch v-model="form.search" :active-value="1" :inactive-value="2" />
                </template>
                <template v-else-if="x.name == 'input'">
                  <el-select v-model="form.input" placeholder="请选择类型" style="width: 200px;">
                    <el-option :value="1" label="文本">文本</el-option>
                    <el-option :value="2" label="选择">选择</el-option>
                    <el-option :value="3" label="时间">时间</el-option>
                    <el-option :value="4" label="链接">链接</el-option>
                  </el-select>
                </template>
                <!-- <template v-else-if="x.name == 'start'">
              <el-input v-model="form.start" :placeholder="'请输入路径'" />
              <el-button @click="getfolderPath">
                获取地址
              </el-button>
            </template> -->
                <template v-else-if="x.name == 'level'">
                  <el-select v-model="form.level" placeholder="请选择等级" style="width: 200px;">
                    <el-option :value="1" label="轻">轻</el-option>
                    <el-option :value="2" label="重">重</el-option>
                    <el-option :value="3" label="缓">缓</el-option>
                    <el-option :value="4" label="急">急</el-option>
                  </el-select>
                  <!-- <el-slider style="width: 300px;margin-left: 10px;" v-model="form.progress" :step="10" show-stops />  -->
                </template>
                <template v-else-if="x.name == 'icon'">
                  <el-input v-model="form.icon" :placeholder="'请输入' + x.title" style="width: 100px;" />
                  <div :class="'iconfont icon-' + form.icon" style="margin: 0 10px;"></div>
                  <el-button @click="() => { showSelectIcon = true }">选择图标</el-button>
                </template>
                <template v-else-if="x.name == 'elicon'">
                  <el-input v-model="form.elicon" :placeholder="'请输入' + x.title" style="width: 100px;" />
                  <el-icon style="font-size: 24px;margin: 0 10px;">
                    <component :is="elicons[form.elicon]" />
                  </el-icon>
                  <el-button @click="() => { showSelectElIcon = true }">选择图标</el-button>
                </template>
                <el-input v-else v-model="form[x.name]" :placeholder="'请输入' + x.title" @keyup.enter="submit" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
          <div>
            <el-button type="primary" @click="handleLast" v-if="formType == 1">上一个</el-button>
            <el-button type="primary" @click="submit">保 存</el-button>
            <el-button @click="() => { state.open = false }">取 消</el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog title="选择EL图标" v-model="showSelectElIcon" width="800px">
        <div>{{ eliconArr[selectElIdx].name }}</div>
        <div class="elicon-list">
          <div v-for="(x, y) in eliconArr" @click="selectElIcon(y)" :key="y" :class="selectElIdx == y ? 'active' : ''">
            <el-icon>
              <component :is="elicons[x.name]" />
            </el-icon>
            {{ }}
          </div>
        </div>
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
          <el-button type="primary" @click="saveElIcon">保 存</el-button>
          <el-button @click="() => { showSelectElIcon = false }">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择图标" v-model="showSelectIcon" width="800px">
        <div>{{ glyphs[selectIdx].font_class }}</div>
        <div class="icon-list">
          <div v-for="(x, y) in glyphs" @click="selectIcon(y)" :key="y" :class="selectIdx == y ? 'active' : ''">
            <div :class="'iconfont icon-' + x.font_class" :title="x.font_class"></div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
          <el-button type="primary" @click="saveIcon">保 存</el-button>
          <el-button @click="() => { showSelectIcon = false }">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="批量上传" v-model="isUp" width="800px">
        <el-upload class="upload-demo" drag multiple :on-change="upExcel" :auto-upload="false">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽到此或者<em>点击上传文件</em>
          </div>
        </el-upload>
        <el-table :data="dataList" style="width: 100%" v-if="dataList.length > 0" border>
          <template v-for="(x, y) in columnList" :key="y">
            <el-table-column :prop="x.name" :label="x.title" width="200" align="center" />
          </template>
        </el-table>
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
          <el-button type="primary" @click="saveUp">保 存</el-button>
          <el-button @click="() => { isUp = false }">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="tableName + ' 表结构'" v-model="isStructure" width="800px">
        <el-table :data="state.columns" style="width: 100%">
          <el-table-column prop="cid" label="id" width="50" />
          <el-table-column prop="name" label="名称" width="180" />
          <el-table-column prop="type" label="类型" width="180" />
          <el-table-column prop="pk" label="主键" width="80" />
          <el-table-column prop="notnull" label="空" width="80" />
          <el-table-column prop="dflt_value" label="默认" width="80" />
        </el-table>
      </el-dialog>
      <el-dialog title="整体排序" v-model="isSort" width="800px">
        <el-tree style="max-width: 600px" :data="sortList" draggable default-expand-all node-key="id"
          @node-drop="handleDrop" />
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: right;">
          <el-button type="primary" @click="saveSort">保 存</el-button>
          <el-button @click="() => { isSort = false }">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="数据详情" v-model="isMessage" width="800px">
        <el-descriptions title="" :column="2" border>
          <template v-for="(x, y) in state.searchColumns" :key="y">
            <el-descriptions-item v-if="x.name == 'icon'" :label="x.title" align="center">
              <span :class="'iconfont icon-' + detail.icon"></span>
            </el-descriptions-item>
            <el-descriptions-item v-else-if="x.name == 'elicon'" :label="x.title" align="center">
              <el-icon>
                <component :is="elicons[detail.elicon]" />
              </el-icon>
            </el-descriptions-item>
            <el-descriptions-item v-else-if="x.name == 'color'" :label="x.title" align="center">
              <div :style="{ width: '20px', height: '20px', background: detail.color, margin: '0 auto' }"></div>
            </el-descriptions-item>
            <el-descriptions-item v-else-if="x.name == 'start'" :label="x.title" align="center">
              <el-button @click="goStart(detail)">启动</el-button>
            </el-descriptions-item>
            <el-descriptions-item v-else :label="x.title" align="center">
              <div class="descriptions-content ellipsis">
                {{ detail[x.name] }}
              </div>
            </el-descriptions-item>
          </template>
        </el-descriptions>
        <el-descriptions title="" :column="3" border style="margin-top: 5px;">
          <el-descriptions-item label="id" align="center">
            {{ detail.id }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" align="center">
            {{ detail.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="修改时间" align="center">
            {{ detail.update_time }}
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import * as XLSX from 'xlsx';
import { glyphs } from '@/assets/font/iconfont.json'
import { checkData, queryData, getColumnList, editData, delData, addData, batchSort, getAllData } from '@/apis/mysql'
import { computed, onMounted, reactive, ref, getCurrentInstance } from 'vue';
import elicons from '@/utils/elicons';
import options from '@/utils/options';
const eliconArr = []
for (let i in elicons) {
  eliconArr.push({
    name: i
  })
}

const { proxy } = getCurrentInstance()
const state = reactive({
  tables: [],
  columns: [],
  searchColumns: [],
  lists: [],
  title: '',
  open: false,
})
const sizes = [10, 20, 50, 100, 200]
const menus = ref([])
const sortList = ref([])
const pidOptions = ref([])
const formType = ref(0)
const form = ref({})
const formRef = ref(null)
const isCollapse = ref(false)
const isBatch = ref(false)
const isUp = ref(false)
const showSearch = ref(false)
const isStructure = ref(false)
const isMessage = ref(false)
const isSort = ref(false)
const searchParams = reactive({})
const searchRef = ref(null)
const detail = ref(null)
const total = ref(0)
const tableName = ref('columns')
const word = 'abcdefghijklmnopqrstuvwxyz'
const columnList = ref([])
const dataList = ref([])
const multipleSelection = ref([])
const typeOptions = ref([])

const queryParams = reactive({
  page: 1,
  show: 10
})

onMounted(() => {
  // document.title = '数据管理'
  getAllTable()
})

// 所有表格
function getAllTable() {
  let arr = []
  queryData({
    table: 'shows',
    query: {
      page: 1,
      show: 999
    }
  }).then(res => {
    menus.value = proxy.$global.arrayToTree(proxy.$global.reSort(res.data, 'sort'), 'pid', 0)
    menus.value.map(x => {
      arr.push(...x.children)
    })
    state.tables = arr
    selectMenu(tableName.value)
  })
}

// 选择表格
function selectMenu(e) {
  let table = e
  tableName.value = table
  showSearch.value = false
  checkData({ table }).then(res => {
    state.columns = res
    getColumns(table)
  })
}

function getTypeOptions(table) {
  const arr = [
    {
      label: '全部',
      value: 0
    }
  ]
  if (options[table]) (
    options[table].map((x, y) => {
      arr.push({
        label: x,
        value: y + 1
      })
    })
  )
  typeOptions.value = arr
  // console.log(arr)
}

// 父级列表
function getPidOptions() {
  const params = {
    table: tableName.value,
    data: {
      pid: '0'
    },
    query: {
      page: 1,
      show: 100
    }
  }
  queryData(params).then(res => {
    const arr = [
      {
        label: '全部',
        value: 0
      }
    ]
    // console.log(res)
    res.data.map(x => {
      arr.push({
        label: x.title || x.label,
        value: x.id
      })
    })
    pidOptions.value = arr
    // console.log(arr)
  })
}

// 获取参数列表
function getColumns(table) {
  getColumnList(table).then(res => {
    // console.log(res)
    state.searchColumns = proxy.$global.reSort(res.data, 'sort')
    form.value = {}
    // // console.log(options[table])
    res.data.map(x => {
      if (x.name == 'pid') {
        getPidOptions()
      } else {
        pidOptions.value = []
      }
    })
    if (options[table]) {
      getTypeOptions(table)
    }
    resetSearch()
  })
}

// 重置搜索
function resetSearch() {
  searchRef.value.resetFields()
  queryParams.show = 10
  handleCurrentChange(1)
}

// 分页
function handleCurrentChange(page) {
  queryParams.page = page
  getList()
}

// 每页显示
function handleSizeChange(show) {
  queryParams.show = show
  handleCurrentChange(1)
}

//获取数据
function getList() {
  let table = tableName.value
  const params = {
    table,
    data: searchParams,
    query: queryParams
  }

  if (hasSort(state.columns, 'sort')) {
    params.sort = true
  }

  if (hasSort(state.columns, 'pid')) {
    params.pid = true
  }

  if (hasSort(state.columns, 'type') && tableName.value != 'elements') {
    params.type = true
  }

  queryData(params).then(res => {
    let arr = []
    res.data.map((x, y) => {
      arr.push(x)
    })
    // console.log(res)
    state.lists = arr
    total.value = res.total
  })
}

// 删除对象所有字段
function deleteAllProperties(obj) {
  for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      delete obj[prop];
    }
  }
}

function getInputLabel(index) {
  return ['文本', '选择', '输入', '跳转'][index - 1]
}

const menuWidth = computed(() => {
  let width = isCollapse.value ? 64 : 200
  return `${width}px`
})

//
const contentWidth = computed(() => {
  let width = isCollapse.value ? 64 : 200
  return `calc(100% - ${width}px)`
})

// 上传数据
function saveUp() {
  const table = 'test'
  for (let i = 0; i < dataList.value.length; i++) {
    dataList.value[i].create_time = proxy.$global.formatDataTime(new Date())
    dataList.value[i].update_time = proxy.$global.formatDataTime(new Date())
    addData({ table, data: dataList.value[i] }).then(res => {
      if (res.code == 1000) {
        proxy.$global.success(res.msg)
        getList()
        state.open = false
      }
    })
  }
}

// 间隔触发程序
function arrSetInterval(arr, fn) {
  let count = 0
  let timer = setInterval(() => {
    count++
    fn(0)
    if (count == arr.length) {
      clearInterval(timer)
    }
  })
}

// 排序
const sortData = () => {
  isSort.value = true
  const arr = []
  state.lists.map(x => {
    arr.push({
      label: x.title || x.label,
      id: x.id
    })
  })
  sortList.value = arr
}

// 保存排序
const saveSort = () => {
  let arr = []
  sortList.value.map((x, y) => {
    arr.push({
      id: x.id,
      label: x.label,
      sort: y + 1
    })
  })
  batchSort({
    table: tableName.value,
    sorts: arr
  }).then(res => {
    isSort.value = false
    getList()
  })
}

const handleDrop = (
  draggingNode,
  dropNode,
  dropType,
  ev
) => {
  // console.log('tree drop:', dropNode.label, dropType)
}

// 上传表格
function upExcel(res) {
  const reader = new FileReader();
  reader.onload = function (e) {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
    const worksheet = workbook.Sheets[sheetName]; // 获取工作表数据
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // 转换为JSON数据，header: 1 表示第一行作为标题行
    // data.value = jsonData; // 更新data引用，以便在模板中显示数据
    // // console.log(jsonData)
    let columns = []
    let tableData = []
    jsonData[0].map((x, y) => {
      columns.push({
        name: x,
        title: x
      })
    })
    jsonData.map((x, y) => {
      if (y > 0) {
        tableData.push(arrToObj2(x, columns))
      }
    })
    columnList.value = columns
    dataList.value = tableData
  };
  reader.readAsArrayBuffer(res.raw);
}

// 数组转成对象
function arrToObj(arr) {
  const obj = []
  arr.map((x, y) => {
    obj[word[y]] = x
  })
  return obj
}

// 数组转成对象2
function arrToObj2(arr, list) {
  const obj = []
  arr.map((x, y) => {
    obj[list[y].title] = x
  })
  return obj
}

// 打开链接
function goToLink(href) {
  proxy.$system.openWeb(href)
}

// 打开软件
function goStart(start) {
  if (start.includes('.bat')) {
    proxy.$system.openFile(start)
  } else {
    proxy.$system.openWeb(start)
  }
}


const selectIdx = ref(0)
const selectElIdx = ref(0)
const showSelectIcon = ref(false)
const showSelectElIcon = ref(false)

// 选择图标
function selectIcon(y) {
  selectIdx.value = y
}

function selectElIcon(y) {
  selectElIdx.value = y
}

// 保持el图标
function saveElIcon() {
  let obj = form.value
  obj.elicon = eliconArr[selectElIdx.value].name
  form.value = obj
  showSelectElIcon.value = false
}

// 保存选择
function saveIcon() {
  let obj = form.value
  obj.icon = glyphs[selectIdx.value].font_class
  form.value = obj
  showSelectIcon.value = false
}

function setPidLabel(pid) {
  let str = ''
  let arr = pidOptions.value.filter(x => x.value == pid)
  if (arr.length > 0) {
    if (arr[0].label != '全部') {
      str = arr[0].label
    }
  }
  return str
}

function setTypeLabel(type) {
  let str = ''
  let arr = typeOptions.value.filter(x => x.value == type)
  if (arr.length > 0) {
    if (arr[0].label != '全部') {
      str = arr[0].label
    }
  }
  return str
}



// 导出excel
function batchExcel() {
  isUp.value = true
}

// 显示搜索
function handleSearch() {
  showSearch.value = !showSearch.value
}


function handleLast() {
  let row = state.lists[state.lists.length - 1]
  // if (tableName.value) {
  //   const str = row.name.slice(0, 3)
  //   const num = row.name.slice(3)
  //   row.name = str + (parseInt(num) + 1)
  //   if (row.sort) {
  //     row.sort = parseInt(row.sort) + 1
  //   }
  // }
  delete row.id
  form.value = row
}

// 批次
function handleBatch() {
  isBatch.value = !isBatch.value
  multipleSelection.value = []
}

// 处理数据
function handleSelectionChange(arr) {
  multipleSelection.value = arr
}

// 详情
function handleDetail(row) {
  detail.value = row
  isMessage.value = true
}

// 添加
function handleAdd() {
  state.title = '新增'
  state.open = true
  formType.value = 1
  form.value = {}
}

// 编辑
function handleUpdate(row) {
  state.title = '修改'
  state.open = true
  form.value = row
  formType.value = 2
}

// 删除
function handleDelete(row) {
  let option = {
    title: '删除数据！',
    content: '是否确认删除id为"' + row.id + '"的数据项？',
    type: 'Warning'
  }
  let table = tableName.value
  proxy.$global.confirm(option).then(() => {
    delData(table, row.id).then((res) => {
      proxy.$global.success(res.msg)
      getList()
    })
  }).catch(() => { });
}

// 关闭
function handleClose(e) {
  // console.log(e)
}

// 伸缩
function handleCollapse() {
  isCollapse.value = !isCollapse.value
}

function hasSort(arr, str) {
  let flag = false
  arr.map(x => {
    if (x.name == str) {
      flag = true
    }
  })
  return flag
}





// 提交数据
function submit() {
  let table = tableName.value
  let data = proxyToObject(form.value)
  data.update_time = proxy.$global.formatDataTime(new Date())
  // // console.log(form.value.begin)
  // if (data.begin) {
  //   data.begin = proxy.$global.formatDataTime(form.value.begin).split('  ')[0]
  //   data.end = proxy.$global.formatDataTime(form.value.end).split('  ')[0]
  // }
  if (formType.value == 1) {
    data.create_time = proxy.$global.formatDataTime(new Date())
    addData({ table, data }).then(res => {
      if (res.code == 1000) {
        proxy.$global.success(res.msg)
        getList()
        state.open = false
      }
    })
  } else {
    editData({ table, data }).then(res => {
      // // console.log(res)
      if (res.code == 1000) {
        proxy.$global.success(res.msg)
        getList()
        state.open = false
      }
    })
  }
}

// proxy转对象
function proxyToObject(proxy) {
  const obj = {};
  for (let prop in proxy) {
    if (Reflect.has(proxy, prop)) { // 使用Reflect.has检查属性是否存在，避免不必要的错误
      obj[prop] = Reflect.get(proxy, prop);
    }
  }
  return obj;
}

// 对象转数组
function objToArr(obj) {
  let arr = []
  for (let i in obj) {
    arr.push(obj[i])
  }
  return arr
}

// 获取对象拼成数组
function getObjAttr(obj) {
  let arr = []
  for (let i in obj) {
    arr.push(i)
  }
  return arr
}

// 导出表格数组
function objArrToExcelArr(list) {
  let arr = []
  arr.push(getObjAttr(list[0]))
  list.map((x) => {
    arr.push(objToArr(x))
  })
  // console.log(arr)
  return arr
}

// 导出Excel
function exportToExcel() {
  // 将数据转换为工作表
  let arr = objArrToExcelArr(multipleSelection.value)
  const ws = XLSX.utils.aoa_to_sheet(arr);
  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  // 导出Excel文件
  XLSX.writeFile(wb, tableName.value + ".xlsx");
  // console.log(arr, ws, wb)
}

function allExport() {
  getAllData(tableName.value).then(res => {
    console.log(res.data)
    // 将数据转换为工作表
    let arr = objArrToExcelArr(res.data)
    const ws = XLSX.utils.aoa_to_sheet(arr);
    // 创建工作簿并添加工作表
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    // 导出Excel文件
    XLSX.writeFile(wb, tableName.value + ".xlsx");
    // console.log(arr, ws, wb)
  })
}

// 导出json
function exportToJSON() {
  let arr = JSON.stringify(multipleSelection.value)
  const path = `D:/cyc/files/json/${tableName.value}.json`
  proxy.$system.writeFile(path, arr).then(res => {
    // console.log(res)
    proxy.$global.success('导出成功')
  })
}
</script>

<style scoped lang="scss">
.manager {
  width: 100%;
  height: 100%;
  display: flex;
  // position: relative;

  .left {
    // width: 200px;
    height: 100%;
    border-right: 1px solid #fff;
    position: relative;

    .left-tilte {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .left-menu {
      width: 100%;
      height: 100%;
      // height: calc(100% - 40px);
      overflow: auto;
      position: absolute;
      background-color: #fff;

      >div {
        width: 100%;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }

      .active {
        color: aqua;
      }

      .el-sub-menu {
        >div {
          width: 100%;
          height: 100%;

          >span {
            color: #000;
          }
        }
      }
    }
  }

  .right {
    // width: calc(100% - 200px);
    height: 100%;

    .content {
      width: 100%;
      height: 100%;
      padding: 10px;
      overflow: auto;
      background-color: #fff;

      >div {
        margin-bottom: 10px;
      }
    }
  }

  .icon-list {
    >div {
      width: 36px;
      height: 36px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #fff;

      >div {
        font-size: 20px;
      }
    }

    .active {
      border: 1px solid darkblue;
    }
  }

  .elicon-list {
    display: flex;
    flex-wrap: wrap;

    >div {
      width: 36px;
      height: 36px;
      font-size: 20px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #fff;
    }

    .active {
      border: 1px solid darkblue;
    }
  }
}

// .el-descriptions__table {
//   width: 100%;
//   height: 100%;

//   .descriptions-content {
//     width: 100%;
//     height: 100%;
//   }
// }</style>
